package com.insurance.controller;

import com.alibaba.fastjson.JSON;
import com.insurance.common.Contants;
import com.insurance.common.ResultData;
import com.insurance.mapper.LoginRegisterMapper;
import com.insurance.realms.MyRealm;
import com.insurance.service.LoginRegisterService;
import com.insurance.service.ProducerService;
import com.insurance.utils.JwtUtil;
import io.swagger.annotations.*;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: 朱雄
 * Date: 2020/10/26 17:39
 * Description:
 * Version: V1.0
 */
@Api(value = "登录注册",tags = "登录注册接口API")
@Controller
public class LoginRegisterController {

    @Autowired
    private ResultData resultData;

    @Autowired
    private LoginRegisterService longinRegisterService;

    @Autowired
    private ProducerService println;
    @Autowired
    private LoginRegisterMapper loginRegisterMapper;

    @ResponseBody
    @GetMapping(value = "/login.do",produces = "application/json;charset=utf-8")
    @ApiOperation(value = "登录",notes = "登录接口",httpMethod = "get",response = ResultData.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user_phone",value = "用户电话",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "user_pwd",value = "用户密码",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "remember_pwd",value = "是否记住密码",required = true,dataType = "String",paramType = "query")
    })
    @ApiResponses({
            @ApiResponse(code=200,message="登录接口"),
            @ApiResponse(code=500,message="后台服务错误"),
            @ApiResponse(code=501,message="登录失败")
    })
    public ResultData login(String user_phone,String user_pwd,String remember_pwd){
        System.out.println("user_phone:"+user_phone);
        System.out.println("user_pwd:"+user_pwd);
        System.out.println("remember_pwd:"+remember_pwd);
        String token= JwtUtil.createJwt(UUID.randomUUID().toString(),"zhuxiong",JwtUtil.generalSubject(user_phone),JwtUtil.TTMILLS);
        Subject subject = SecurityUtils.getSubject();
        if(!subject.isAuthenticated()){
            System.out.println("==============Subject===============");
            //2、获取Token : 从前端传
            UsernamePasswordToken stoken = new UsernamePasswordToken(user_phone,user_pwd);
            //3、登录
            subject.login(stoken);
            //记住密码
            if ("1".equals(remember_pwd)){
                stoken.setRememberMe(true);
            }
        }
        //登录成功后是否记住密码
         List<Map> list= longinRegisterService.queryInfoAll(user_phone);
        longinRegisterService.updateUserLastTime(user_phone);
        resultData.setCode(Contants.SUCCESS);
        resultData.setMsg("登录成功");
        resultData.setToken(token);
        resultData.setData(list);
        return resultData;
    }

    //忘记密码
    @ResponseBody
    @GetMapping(value = "/forgetPassword.do",produces = "application/json;charset=utf-8")
    @ApiOperation(value = "忘记密码",notes = "忘记密码",httpMethod = "post",response = ResultData.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user_phone",value = "用户电话",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "user_pwd",value = "用户密码",required = true,dataType = "String",paramType = "query"),
              })
    @ApiResponses({
            @ApiResponse(code=200,message="修改成功"),
            @ApiResponse(code=500,message="后台服务错误"),
    })
    public ResultData forgetPassword(String user_phone,String user_pwd){
        resultData= longinRegisterService.forgetPassword(user_phone,user_pwd);
        return resultData;
    }

    @ResponseBody
    @GetMapping(value = "/abnormal.do",produces = "application/json;charset=utf-8")
    @ApiOperation(value = "忘记密码",notes = "忘记密码",httpMethod = "post",response = ResultData.class)
    @ApiResponses({
            @ApiResponse(code=200,message="修改成功"),
            @ApiResponse(code=500,message="后台服务错误"),
    })
    public ResultData abnormal(){
            ResultData resultData=new ResultData();
            resultData.setCode(Contants.FAILURE);
            resultData.setMsg("权限不足");
        return resultData;
    }

    @ResponseBody
    @GetMapping(value = "/exit.do",produces = "application/json;charset=utf-8")
    @ApiOperation(value = "忘记密码",notes = "忘记密码",httpMethod = "post",response = ResultData.class)
    @ApiResponses({
            @ApiResponse(code=200,message="修改成功"),
            @ApiResponse(code=500,message="后台服务错误"),
    })
    public ResultData exit(){
        ResultData resultData=new ResultData();
        Subject subject = SecurityUtils.getSubject();
            //2、获取Token : 从前端传
          //  UsernamePasswordToken stoken = new UsernamePasswordToken(user_phone,user_pwd);
            //3、登录
            System.out.println("===============成功退出");
            subject.logout();
            resultData.setCode(Contants.SUCCESS);
            resultData.setMsg("成功退出");
        return resultData;
    }

    @ResponseBody
    @GetMapping(value = "/sendCode.do",produces = "application/json;charset=utf-8")
    @ApiOperation(value = "获取验证码",notes = "获取验证码口",httpMethod = "get",response = ResultData.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user_phone",value = "用户电话",required = true,dataType = "String",paramType = "query"),
    })
    @ApiResponses({
            @ApiResponse(code=200,message="验证码发送成功"),
            @ApiResponse(code=500,message="后台服务错误"),
    })
    public ResultData forgetPassword(String user_phone){
       Map map= longinRegisterService.queryByUserPhone(user_phone);
       if (map==null){
           resultData.setMsg("手机号不存在");
           resultData.setCode(Contants.FAILURE);
           return resultData;
       }
        ResultData resultData=new ResultData();
        String clientPhone = user_phone;
        int mobile_code = (int)((Math.random() * 9 + 1) * 100000); //随机生成6位数
        String content = "您的验证码是：" + mobile_code + "。请不要把验证码泄露给其他人。";
        // 添加参数
        HashMap<String, String> params = new HashMap<>();
        params.put("account","C44195745");                              //查看用户名是登录用户中心->验证码短信->产品总览->APIID
        params.put("password","e6cc5d6ae20ba982025879312e22a5a8 ");    //查看密码请登录用户中心->验证码短信->产品总览->APIKEY
        params.put("mobile",clientPhone);                             // 发送给哪一个手机号
        params.put("content",content);                                   // 发送的文字
        // 实例化HTTP方法
        HttpPost request = new HttpPost();
        // 封装请求地址
        try {
            request.setURI(new URI("http://106.ihuyi.cn/webservice/sms.php?method=Submit"));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        // 设置参数
        List<NameValuePair> nameValuePairsList = new ArrayList<>();
        // 封装数据值
        for (String name : params.keySet()) {
            String value = params.get(name);
            nameValuePairsList.add(new BasicNameValuePair(name, value));  // gun
        }
        HttpClient client = new DefaultHttpClient();
        try {
            request.setEntity(new UrlEncodedFormEntity(nameValuePairsList, HTTP.UTF_8));
            HttpResponse response = client.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode == 200){	//请求成功
                BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity()
                        .getContent(),"utf-8"));
                StringBuilder sb = new StringBuilder("");
                String line = "";
                String NL = System.getProperty("line.separator");   // apache建议回车使用line.separator(回车)     \n
                while ((line = in.readLine()) != null) {
                    sb.append(line).append(NL);    // 每添加一个值，追加一个回车
                }
                in.close();
                String SubmitResult = sb.toString();
                System.out.println("服务器返回结果内容：" + SubmitResult);
                Document doc = DocumentHelper.parseText(SubmitResult);
                Element root = doc.getRootElement();
                String code = root.elementText("code");
                String msg = root.elementText("msg");
                String smsid = root.elementText("smsid");
                System.out.println("回执状态码：" + code);
                System.out.println("回执消息：" + msg);
                System.out.println("回执ID：" + smsid);

                if("2".equals(code)){
                    System.out.println("短信提交成功");
                    resultData.setCode(Contants.SUCCESS);
                    resultData.setMsg("验证码获取成功");
                    resultData.setData(mobile_code);
                }
            }
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        } finally{
            // Release connection
            request.releaseConnection();
            client.getConnectionManager().shutdown();
        }
        return resultData;
    }


}
